package com.dayou.util;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class RedisUtils {
    private static final Logger log = LoggerFactory.getLogger(RedisUtils.class);

    private RedisTemplate redisTemplate;

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存设置时效时间
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 哈希 添加
     *
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put(key, hashKey, value);
    }

    /**
     * 哈希获取数据
     *
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        return hash.get(key, hashKey);
    }

    /**
     * 列表添加
     *
     * @param k
     * @param v
     */
    public void lPush(String k, Object v) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k, v);
    }

    /**
     * 获取列表长度
     */
    public Long lSize(String k) {
        return redisTemplate.opsForList().size(k);
    }

    /**
     * 列表获取
     */
    public List<Object> lRange(String k, long l, long l1) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k, l, l1);
    }

    /**
     * 集合添加
     */
    public void add(String key, Object value) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key, value);
    }

    /**
     * 集合获取
     */
    public Set<Object> setMembers(String key) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 有序集合添加
     */
    public void zAdd(String key, Object value, double scoure) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key, value, scoure);
    }

    /**
     * 有序集合获取
     */
    public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }


    /**
     * 设置缓存数据
     *
     * @param key          缓存key
     * @param value        缓存value
     * @param cacheLogName 缓存日志打印名称
     */
    public void setJSONCache(String key, Object value, String cacheLogName) {
        cacheLogName = StringUtil.isNullOrEmpty(cacheLogName) ? key : cacheLogName;
        log.info(String.format("正在缓存%s数据 - key[%s]", cacheLogName, key));
        if (this.exists(key)) {
            log.info(String.format("%s缓存key[%s]已存在，正在删除", cacheLogName, key));
            this.remove(key);
            log.info(String.format("%s缓存key[%s]删除完毕", cacheLogName, key));
        }
        String jsonValue = JSONObject.toJSONString(value);
        this.set(key, jsonValue);
        log.info(String.format("%s缓存完毕 - key[%s]", cacheLogName, key));
    }

    /**
     * 获取JSONObject格式缓存并转为泛型
     *
     * @param key   缓存key
     * @param clazz 泛型class
     * @param <T>   泛型类
     * @return 结果
     */
    public <T> T getJavaObjectCache(String key, Class<T> clazz) {
        String jsonStr = this.get(key).toString();
        return JSONObject.parseObject(jsonStr, clazz);
    }

    /**
     * 获取JSONObject格式缓存
     *
     * @param key 泛型
     * @return 结果
     */
    public JSONObject getJSONObjectCache(String key) {
        String jsonStr = this.get(key).toString();
        return JSONObject.parseObject(jsonStr);
    }

    /**
     * 获取JSONArray格式缓存并转为泛型
     *
     * @param key   缓存key
     * @param clazz 泛型class
     * @param <T>   泛型类
     * @return 结果
     */
    public <T> List<T> getJavaListCache(String key, Class<T> clazz) {
        String jsonStr = this.get(key).toString();
        return JSONArray.parseArray(jsonStr, clazz);
    }

    /**
     * 获取JSONArray格式缓存
     *
     * @param key 缓存key
     * @return 结果
     */
    public JSONArray getJSONArrayCache(String key) {
        String jsonStr = this.get(key).toString();
        return JSONArray.parseArray(jsonStr);
    }

    /**
     * 根据条件获取JSONArray格式缓存并转为泛型
     *
     * @param key          缓存key
     * @param clazz        泛型class
     * @param conditionObj 条件
     * @param <T>          泛型类
     * @return 结果
     */
    public <T> List<T> getJavaListCache(String key, Class<T> clazz, T conditionObj) {
        String jsonStr = this.get(key).toString();
        JSONArray arrayAll = JSONArray.parseArray(jsonStr);
        Field[] fields = clazz.getDeclaredFields();
        List<Field> condition = new ArrayList<>();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Object value = field.get(conditionObj);
                if (value != null) {
                    if (field.getType() == String.class) {
                        if ("".equals(value.toString())) {
                            continue;
                        }
                    }
                    condition.add(field);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        JSONArray array = arrayAll.stream().filter(c -> {
            boolean flag = true;
            JSONObject jo = (JSONObject) JSONObject.toJSON(c);
            for (Field field : condition) {
                field.setAccessible(true);
                Object v = jo.get(field.getName());
                if (v == null) {
                    flag = false;
                    break;
                } else {
                    try {
                        Object _v = field.get(conditionObj);
                        if (field.getType() == String.class) {
                            if (!v.toString().contains(_v.toString())) {
                                flag = false;
                                break;
                            }
                        } else {
                            if (!v.equals(_v)) {
                                flag = false;
                                break;
                            }
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
            return flag;
        }).collect(Collectors.toCollection(JSONArray::new));
        return array.toJavaList(clazz);
    }

    @PostConstruct
    private void afterInit() {
        System.out.println("redis工具初始化成功。");
    }
}